package com.zxjbyte.yiyi.framework.web.xss.wrapper;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.zxjbyte.yiyi.framework.common.util.ServletXUtil;
import com.zxjbyte.yiyi.framework.web.filter.YiyiHttpServletRequestWrapper;
import com.zxjbyte.yiyi.framework.web.xss.clean.IXssCleaner;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author zhangxingjia
 * @Date 2023/4/7 18:25
 * @Version: 1.0
 */
public class YiyiXssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    //没被包装过的HttpServletRequest
    private final HttpServletRequest origRequest;
    // 缓存body
    private byte[] body;
    // xss清理器
    private final IXssCleaner xssCleaner;


    public YiyiXssHttpServletRequestWrapper(HttpServletRequest request, IXssCleaner xssCleaner) {
        super(request);
        this.origRequest = request;
        this.xssCleaner = xssCleaner;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (super.getHeader(HttpHeaders.CONTENT_TYPE) == null) {
            return super.getInputStream();
        }

        if (super.getHeader(HttpHeaders.CONTENT_TYPE).startsWith(MediaType.MULTIPART_FORM_DATA_VALUE)) {
            return super.getInputStream();
        }

        if (body == null) {
            body = StrUtil.utf8Bytes(clean(ServletXUtil.getBody(super.getRequest())));
        }

        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

    @Override
    public String getParameter(String name) {
        return clean(super.getParameter(name));
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] parameters = super.getParameterValues(name);
        if (ArrayUtil.isEmpty(parameters)) {
            return parameters;
        }
        for (int i = 0; i < parameters.length; i++) {
            parameters[i] = clean(parameters[i]);
        }
        return parameters;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> map = new LinkedHashMap<>();
        Map<String, String[]> parameters = super.getParameterMap();
        for (String key : parameters.keySet()) {
            String[] values = parameters.get(key);
            for (int i = 0; i < values.length; i++) {
                values[i] = clean(values[i]);
            }
            map.put(key, values);
        }
        return map;
    }

    @Override
    public String getHeader(String name) {
        return clean(super.getHeader(name));
    }

    @Override
    public String getQueryString() {
        return clean(super.getQueryString());
    }

    @Override
    public Object getAttribute(String name) {
        Object value = super.getAttribute(name);
        if (value instanceof String) {
            return clean((String) value);
        }
        return value;
    }

    private String clean(String input){
        return xssCleaner.clean(input);
    }

    /**
     * 获取初始request
     *
     * @return HttpServletRequest
     */
    public HttpServletRequest getOrigRequest() {
        return origRequest;
    }

    /**
     * 获取初始request
     *
     * @param request request
     * @return HttpServletRequest
     */
    public static HttpServletRequest getOrigRequest(HttpServletRequest request) {
        if (request instanceof YiyiHttpServletRequestWrapper) {
            return ((YiyiHttpServletRequestWrapper) request).getOrigRequest();
        }
        return request;
    }

}
